var express = require('express');
var router = express.Router();
var mysql = require('mysql');

//连接数据库
function mysqlConnect() {
    var con = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '12345678',
        database: 'print'
    });
    return con;
}

//CROS跨域设置
function CROS(resCode) {
    resCode.header("Access-Control-Allow-Origin", "*");
    resCode.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    resCode.header("Access-Control-Allow-Headers", "X-Requested-With");
    resCode.header('Access-Control-Allow-Headers', 'Content-Type');
}

//1:完成 2：进行中
//接受任务接口
var acceptTaskApiCode = '/list';
var acceptTaskCode = 'UPDATE my_list SET state=2,user_id=? WHERE id=?';
taskApi(acceptTaskApiCode,acceptTaskCode);

//完成任务接口
var taskApiCode = '/completeList';
var code = 'UPDATE my_list SET state=1,user_id=? WHERE id=?';
taskApi(taskApiCode,code);

//收藏任务接口
var collectionApiCode = '/collection';
var collectionCode = 'UPDATE my_list SET collectionId=? WHERE id=?';
taskApi(collectionApiCode,collectionCode);

//获取附近打印店
var selectPrint = '/printShop';
var shopCode = 'SELECT * FROM pr_print';
selectRoot(selectPrint,shopCode);

//获取任务列表
var api = '/content';
var query = 'SELECT * FROM pr_content';
selectRoot(api,query);

//客户专区
var customerApi = '/customer';
var customerCode = 'SELECT * FROM pr_customer';
selectRoot(customerApi,customerCode);

//注册用户接口
router.post('/register', function(req, res, next) {

    //CROS跨域设置
    CROS(res);

    //创建数据库连接
    var dbConnection = mysqlConnect();
    dbConnection.query('INSERT INTO pr_user SET ?', {
        password: req.body.password,
        email:req.body.email,
        school_num:req.body.school_num,
        school:req.body.school,
        coin:'1000',
        name:body.email
    }, function (err, result) {
        if (err) {
            console.log(err);
        } else {
            res.send("1");
        }
        dbConnection.end();
    });

});

//登录接口
router.get('/login', function(req, res, next) {
    //res.render('index', { title: 'Expres222s' });

    //CROS跨域设置
    CROS(res);
    //创建数据库连接
    var dbConnection = mysqlConnect();

    var query='SELECT * FROM pr_user where email='+req.query.email;

    dbConnection.query(query, function (err, rows, fields) {

        if (err) throw err;
        console.log(rows);
      //  rows.password
        console.log(rows[0].password);

        if(req.query.password == rows[0].password) {
            res.send(JSON.stringify(rows[0]));
        }
        else {
            res.send('密码错误');
        }

        dbConnection.end();

    });
});

//主页获取用户信息
router.get('/user', function(req, res, next) {
    //res.render('index', { title: 'Expres222s' });

    //CROS跨域设置
    CROS(res);
    //创建数据库连接
    var dbConnection = mysqlConnect();

    var query='SELECT * FROM pr_user where id='+req.query.id;

    dbConnection.query(query, function (err, rows, fields) {

        if (err) throw err;
        console.log(rows);
        res.send(JSON.stringify(rows[0]));

        dbConnection.end();

    });
});

//获取商店信息
router.get('/goods', function(req, res, next) {

    //CROS跨域设置
    CROS(res);
    //创建数据库连接
    var dbConnection = mysqlConnect();

    var query='SELECT * FROM pr_goodsList where shopId='+req.query.shopId;

    dbConnection.query(query, function (err, rows, fields) {

        if (err) throw err;
        console.log(rows);
        res.send(JSON.stringify(rows));

        dbConnection.end();

    });
});

router.post('/user', function (req, res, next) {

    //CROS跨域设置
    CROS(res);

    //创建数据库连接
    var dbConnection = mysqlConnect();
    //更新操作
    dbConnection.query('UPDATE pr_user SET coin=? WHERE id=?', [
        req.body.coin,
        req.body.userId
    ], function (err, result) {
        if (err) {
            res.send(err.toString()); //返回错误信息
        } else {
            res.send("成功更新了" + result.affectedRows + "条数据");
        }
        dbConnection.end();
    });

});

//获取个人任务列表
router.get('/list', function(req, res, next) {
    //res.render('index', { title: 'Expres222s' });

    //CROS跨域设置
    CROS(res);
    //创建数据库连接
    var dbConnection = mysqlConnect();
    if(req.query.userId) {

        var query='SELECT * FROM my_list where state>0&&user_id=' + req.query.userId;

        dbConnection.query(query, function (err, rows, fields) {

            if (err) throw err;
            else {
                console.log(JSON.stringify(rows));
                res.send(JSON.stringify(rows));
            }

            dbConnection.end();

        });
    }
    else {

        var query='SELECT * FROM my_list where m_id=' + req.query.m_id;

        dbConnection.query(query, function (err, rows, fields) {

            if (err) throw err;
            else {
                console.log(JSON.stringify(rows));
                res.send(JSON.stringify(rows));
            }

            dbConnection.end();

        });
    }

});

//主页获取用户信息
router.get('/collection', function(req, res, next) {
    //res.render('index', { title: 'Expres222s' });

    //CROS跨域设置
    CROS(res);
    //创建数据库连接
    var dbConnection = mysqlConnect();

    var query='SELECT * FROM my_list where collectionId='+ req.query.userId;

    dbConnection.query(query, function (err, rows, fields) {

        if (err) throw err;
        console.log(rows);
        res.send(JSON.stringify(rows));

        dbConnection.end();

    });
});


//获取用户兑换列表
router.get('/personOrderList', function(req, res, next) {
    //res.render('index', { title: 'Expres222s' });

    //CROS跨域设置
    CROS(res);
    //创建数据库连接
    var dbConnection = mysqlConnect();

    var query='SELECT * FROM pr_person_order where userId='+ req.query.userId;

    dbConnection.query(query, function (err, rows, fields) {

        if (err) throw err;
        console.log(rows);
        res.send(JSON.stringify(rows));

        dbConnection.end();

    });
});

//个人兑换列表
router.post('/personOrderList', function(req, res, next) {

    //CROS跨域设置
    CROS(res);

    //创建数据库连接
    var dbConnection = mysqlConnect();
    dbConnection.query('INSERT INTO pr_person_order SET ?', {
        orderName: req.body.orderName,
        shopId:req.body.shopId,
        goodsId:req.body.goodsId,
        goodsAmout:req.body.goodsAmout,
        goodsRMB:req.body.goodsRMB,
        userId:req.body.userId,
        shopName:req.body.shopName,
        shopAddress:req.body.shopAddress,
        goodsImage:req.body.goodsImage
    }, function (err, result) {
        if (err) {
            console.log(err);
        } else {
            res.send("添加成功");
        }
        dbConnection.end();
    });

});

//搜索商店列表
router.get('/search', function(req, res, next) {
    //res.render('index', { title: 'Expres222s' });

    //CROS跨域设置
    CROS(res);
    //创建数据库连接
    var dbConnection = mysqlConnect();
    if(req.query.ifShop == 1){
        var searchTaskList = `SELECT * FROM pr_print where shopName like '%${req.query.title}%'` ;
        dbConnection.query(searchTaskList, function (err, rows, fields) {
            if (err) throw err;
            console.log(rows);
            res.send(JSON.stringify(rows));

            dbConnection.end();

        });
    }
    else{
        var searchTaskList = `SELECT * FROM pr_print where shopName like '%${req.query.title}%'` ;
        dbConnection.query(searchTaskList, function (err, rows, fields) {
            if (err) throw err;
            console.log(rows);
            res.send(JSON.stringify(rows));
            dbConnection.end();

        });
    }

});

//删除个人任务接口
router.delete('/list', function (req, res, next) {

    //CROS跨域设置
    CROS(res);

    //创建数据库连接
    var dbConnection = mysqlConnect();
    var query='DELETE * FROM my_list where user_id=' + req.query.userId;

    dbConnection.query(query, function (err, result) {
        if (err) {
            res.send(err.toString()); //返回错误信息
        } else {

            console.log(req.query.userId);
            res.send("成功删除了" + result.affectedRows + "条数据");
        }
        dbConnection.end();
    });

});








//接口
//select *接口
function  selectRoot(api,queryCode){
    router.get(api, function(req, res, next) {
        //res.render('index', { title: 'Expres222s' });

        //CROS跨域设置
        CROS(res);
        //创建数据库连接
        var dbConnection = mysqlConnect();

        var query=queryCode;

        dbConnection.query(query, function (err, rows, fields) {

            if (err) throw err;
            else {
                res.send(JSON.stringify(rows));
            }

            dbConnection.end();

        });
    });
}

//任务接口
function taskApi(api,queryCode){
    router.post(api, function (req, res, next) {

        //CROS跨域设置
        CROS(res);
        //创建数据库连接
        var dbConnection = mysqlConnect();

        //更新操作
        dbConnection.query(queryCode, [
            req.body.userId,
            req.body.id
        ], function (err, result) {
            if (err) {
                res.send(err.toString()); //返回错误信息
            } else {
                console.log(result);
                res.send("成功更新了" + result.affectedRows + "条数据");
            }
            dbConnection.end();
        });

    });
}

module.exports = router;